# Title     : TODO
# Objective : TODO
# Created by: Administrator
# Created on: 2019/6/18

createWhenNoExist <- function(f){
    ! dir.exists(f) && dir.create(f)
}

library(gplots)
library(Hmisc)
library(optparse)
library(dplyr)
library(ropls)
library(magrittr)
library(tibble)
library(tidyr)
library(RFmarkerDetector)
library(scales)

option_list <- list(
make_option("--i", default = "AllMet.csv", type = "character", help = "metabolite data file"),
make_option("--g", default = "SampleInfo.csv", type = "character", help = "sample group file"),
make_option("--sc", default = "sample_color.txt", type = "character", help = "sample color file")
)
opt <- parse_args(OptionParser(option_list = option_list))

sampleInfo <- read.csv(opt$g, header = T, stringsAsFactors = F) %>%
    select(c("SampleID", "ClassNote")) %>%
    filter(ClassNote == "QC") %>%
    as.data.frame()

qcSamples <- sampleInfo$SampleID

allData <- read.csv(opt$i, header = T, stringsAsFactors = F) %>%
    select(- c("HMDB", "KEGG", "Class")) %>%
    select(c("Metabolite", qcSamples))

sum<-0
while(TRUE){
    sum=sum+1
}

parent <- "./"
fileName <- paste0(parent, "QC_Samples_Metabolites_RSD_Histogram.pdf")
data <- allData %>%
    rowwise() %>%
    do({
        result <- as.data.frame(.)
        rowData <- result %>%
            select(- c(("Metabolite"))) %>%
            unlist()
        rsdRs <- rsd(rowData)
        result$rsd <- rsdRs
        result
    })
plotData <- data
print(plotData$rsd)

p <- ggplot(plotData, mapping = aes(rsd)) +
    xlab("RSD") +
    theme_bw(base_size = 8.8, base_family = "Times") +
    theme(axis.text.x = element_text(size = 9, vjust = 0.5),
    axis.text.y = element_text(size = 8.8), legend.position = 'right',
    axis.title.y = element_text(size = 11),
    legend.text = element_text(size = 6), axis.title.x = element_text(size = 11)
    ) +
    geom_histogram(aes(y=..density..),fill = "lightblue", color = "black") +
    geom_density(color = "black")

ggsave(limitsize = FALSE,fileName, p, width = 8, height = 8)

